import Vue from 'vue'
import store from '@/store/index'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'

// 和首页相关的我们默认加载，和首页同一级页面我们进行改造
const Login  =() => import('../views/login')
const Search  =() => import('@/views/search')
const Searchlist =() => import('@/views/search/searchlist')
const Prodetail =() => import('@/views/prodetail')
const Pay  =() => import('@/views/pay')
const Myorder  =() => import('@/views/myorder')

// 二级路由
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import Home from '@/views/layout/home'
import User from '@/views/layout/user'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    { path: '/', component: Layout,
      redirect: '/home',
      children: [
        { path: '/home', component: Home },
        { path: '/category', component: Category },
        { path: '/cart', component: Cart },
        { path: '/user', component: User }
      ]
    },
    { path: '/myorder', component: Myorder },
    { path: '/pay', component: Pay },
    { path: '/prodetail/:id', component: Prodetail },
    { path: '/search', component: Search},
    { path: '/searchlist', component: Searchlist},
  ]
})

// 需要验证的页面（ - 后期可以加到数组之中 -）
const authUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  // 判断访问的页面是否在 数组之中
  // 如果不是的话就直接访问
  if(!authUrls.includes(to.path)) {
    next()
    return
  }

  let Checktoken = store.getters.token
  if( Checktoken )
  {
    next()
  }else{
    next('/login')
  }
})

export default router
